package org.sraosha.framework.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 和本地参数相关的工具类
 */
public class LocalUtils {

    /**
     * 获取MAC地址。
     * 注意：在Linux系统上会取到多个MAC，但只返回第一个
     *
     * @return
     */
    public static String getMacAddress() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            // windows操作系统
            StringBuilder stringBuilder = null;
            try {
                InetAddress ip = InetAddress.getLocalHost();
                NetworkInterface network = NetworkInterface.getByInetAddress(ip);
                byte[] mac = network.getHardwareAddress();
                stringBuilder = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    stringBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            // unix/linux操作系统
            List<String> macAddressList = new ArrayList<>();
            try {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                while (networkInterfaces.hasMoreElements()) {
                    NetworkInterface networkInterface = networkInterfaces.nextElement();
                    byte[] macAddress = networkInterface.getHardwareAddress();
                    if (macAddress != null) {
                        StringBuilder macBuilder = new StringBuilder();
                        for (int i = 0; i < macAddress.length; i++) {
                            macBuilder.append(String.format("%02X%s", macAddress[i], (i < macAddress.length - 1) ? "-" : ""));
                        }
                        macAddressList.add(macBuilder.toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return macAddressList.get(0);
        } else {
            return null;
        }
    }
}
